package com.example.tnot.Teacher.CoursePart.CourseInternal.CourseDetailHome.Infor;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tnot.R;
import com.example.tnot.Teacher.BaseFragment.BaseBackFragment;
import com.example.tnot.Teacher.CoursePart.CourseInternal.CourseDetailHome.Infor.Adapter.rvInformationListAdapter;
import com.example.tnot.Teacher.CoursePart.CourseInternal.CourseDetailHome.Infor.ItemBean.Infor;
import com.example.tnot.Util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

public class InforHomeFragment extends BaseBackFragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int REQUEST_IMAGE_PICK = 2;
    View view;
    ImageView iv_add, iv_back;
    private PopupWindow popupWindow;
    private Bitmap imageBitmap;
    private TextView tv_no_infor;
    private RecyclerView rv_infor;
    private List<Infor> Data;

    private Uri selectedImageUri;
    public InforHomeFragment() {
        // Required empty public constructor
    }

    public static InforHomeFragment newInstance(String param1, String param2) {
        InforHomeFragment fragment = new InforHomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.course_infor_home_fragment, container, false);
        InitData();
        tv_no_infor = view.findViewById(R.id.tv_no_infor);

        //如果列表为不为空，则隐藏TextView
        if(!Data.isEmpty()){
            tv_no_infor.setVisibility(View.GONE);

        }
        rv_infor = view.findViewById(R.id.rv_infor);
        rv_infor.setAdapter(new rvInformationListAdapter(Data));
        rv_infor.setLayoutManager(new LinearLayoutManager(getContext()));

        iv_add = view.findViewById(R.id.iv_add);
        iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_no_infor = view.findViewById(R.id.tv_no_infor);
                if (tv_no_infor.getVisibility() == View.VISIBLE && Data.isEmpty()) {
                    tv_no_infor.setVisibility(View.GONE);
                }
                showPopupWindow(v);
            }
        });

        iv_back = view.findViewById(R.id.back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(v);
                navController.navigateUp();
            }
        });
        return view;
    }

    private void InitData() {
        Data = new ArrayList<>();
        Data.add(new Infor("数学家庭作业", R.drawable.information_file, "30MB"));
        Data.add(new Infor("英语家庭作业", R.drawable.information_file, "20MB"));
        Data.add(new Infor("语文家庭作业", R.drawable.information_file, "10MB"));
        Data.add(new Infor("物理家庭作业", R.drawable.information_file, "15MB"));

    }

    private void showPopupWindow(View v) {
        // 避免重复创建
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            return;
        }

        // 加载布局
        View popupView = LayoutInflater.from(getContext()).inflate(R.layout.popup_add_infor_menu, null);

        // 创建PopupWindow，宽度为铺满内容，高度为包裹内容
        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        // 设置背景，否则部分区域无法点击消失
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//        // 设置点击外部消失
        popupWindow.setOutsideTouchable(true);
        // 设置动画样式
        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        //调用手机摄像头拍摄
        popupView.findViewById(R.id.ll_TakePhoto).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用系统相机
                if (getActivity() != null) {
                    if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        // 请求相机权限
                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 100);
                        ToastUtil.showCustomToast(getContext(), "请在权限请求中授予相机权限", Toast.LENGTH_SHORT);
                    } else {
                        // 已有权限，启动相机
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                            startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
                        } else {
                            Toast.makeText(getContext(), "无法启动相机应用", Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                popupWindow.dismiss();
            }
        });
        //调用拍照
        popupView.findViewById(R.id.ll_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用系统相册
                if (getActivity() != null) {
                    Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    if (galleryIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                        startActivityForResult(galleryIntent, REQUEST_IMAGE_PICK);
                    } else {
                        Toast.makeText(getContext(), "无法启动相册应用", Toast.LENGTH_SHORT).show();
                    }
                }
                popupWindow.dismiss();
            }
        });

        popupView.findViewById(R.id.ll_collection).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(view);
                navController.navigate(R.id.action_inforHomeFragment_to_collectFragment2);
                popupWindow.dismiss();
            }
        });
        popupView.findViewById(R.id.ll_file).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(view);
                navController.navigate(R.id.action_inforHomeFragment_to_fileFragment2);
                popupWindow.dismiss();
            }
        });

        popupView.findViewById(R.id.ll_import).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                popupWindow.dismiss();
            }
        });
        popupView.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        // 显示PopupWindow
        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

        // 添加 PopupWindow 消失监听器
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // 当 PopupWindow 消失时，根据数据列表是否为空来决定是否显示 tv_no_infor
                if (tv_no_infor != null) {
                    if (Data.isEmpty()) {
                        tv_no_infor.setVisibility(View.VISIBLE);
                        if (tv_no_infor != null) {
                            tv_no_infor.setVisibility(View.VISIBLE);
                        }
                    } else {
                        tv_no_infor.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 100) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以启动相机
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (getActivity() != null && cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                    startActivity(cameraIntent);
                } else {
                    ToastUtil.showCustomToast(getContext(), "无法启动相机应用", Toast.LENGTH_SHORT);
                }
            } else {
                // 权限被拒绝
                ToastUtil.showCustomToast(getContext(), "相机权限被拒绝，无法使用相机功能", Toast.LENGTH_SHORT);
            }
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case REQUEST_IMAGE_CAPTURE:
                    // 处理拍摄的照片
                    if (data != null && data.getExtras() != null) {
                        // 获取缩略图
                         imageBitmap = (Bitmap) data.getExtras().get("data");
                        // 如果需要完整图片，需要在Intent中指定保存路径
                        ToastUtil.showCustomToast(getContext(), "照片拍摄成功", Toast.LENGTH_SHORT);
                    }
                    break;
                case REQUEST_IMAGE_PICK:
                    // 处理从相册选择的照片
                    if (data != null) {
                         selectedImageUri = data.getData();
                        // 可以使用selectedImageUri来访问选中的图片
                        ToastUtil.showCustomToast(getContext(), "图片选择成功", Toast.LENGTH_SHORT);
                    }
                    break;
            }
        }
    }
}